import json
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
import base64

# 公钥和私钥字符串
PUBLIC_KEY_STR = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC38ieLJREITIxlnpKWSZ9ztRsn9ECqAe2CAICyN9xy5wk1oyPP9Shvze+HYVGzEk/ekok7HehIl5Q9OK1WkwOch82NF/IaMZcGp1+ZTyHJl3tjPh5Y5kdy9i+GlV6vbU0mKoec3jq/VBD2ScKb4piR3BoR0OPaW2HAxwZxDhCpKQIDAQAB
-----END PUBLIC KEY-----"""

PRIVATE_KEY_STR = """-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALfyJ4slEQhMjGWekpZJn3O1Gyf0QKoB7YIAgLI33HLnCTWjI8/1KG/N74dhUbMST96SiTsd6EiXlD04rVaTA5yHzY0X8hoxlwanX5lPIcmXe2M+HljmR3L2L4aVXq9tTSYqh5zeOr9UEPZJwpvimJHcGhHQ49pbYcDHBnEOEKkpAgMBAAECgYAIdqFz5SHUXUxI6SvCszK9VMgB9bqrb9EFHh+Nw6T2mvN5Jq9RRE0G3uVuV8+V4wnuelTK1eiP/XxuOC8+iF9eNlapSOxAXfjdwxf6hYjPlVm2FtBaiC/hnwjzFJLvOxaI4D9tE1fCX+zSDKe8FY50vbmaSj4YKMzhnJyg/W61YQJBAPlBZKGX37oz+104SKSCjeLLlkyMIZjPJZldKw5mBoJWEHmGelCT+uchKIZ4PJxk+jBVuPun3EqsHMWOMl2JUiECQQC87FvGsedU/nDn15trFExCBGraKlMEuDGbo/CzuNfzFQ6OpefVf/4muwU8PFqvrG4xhCQ1jPOD1rSSdJiiUAYJAkEArJDul8XrGiI1DCQUfvj4PKWQyCxYclAwCs7rKUvPg9sMCubktfbNxck6ImcKJ4jtghtHN8vOg1BHlyrMid+xoQJBALRifZKvJPErbMSBQh0wqUtTim66gL/92yf/lYEUmeS4k0iysjRRXGrAoVQNUI1x91kCEcyrw4t7Qrif6Wj5PXkCQQDo+dcqrGfExV0252KnpQuAM/NA1XvfBjo3gQrd2Sa7DPVkqwAmOOWEAnSxPl+VCVKcvDvXobwXSS5giADXcXG4
-----END PRIVATE KEY-----"""

# 加载公钥和私钥
def load_public_key(pem_str):
    pem_bytes = pem_str.encode('utf-8')
    return serialization.load_pem_public_key(
        pem_bytes,
        backend=default_backend()
    )

def load_private_key(pem_str):
    pem_bytes = pem_str.encode('utf-8')
    return serialization.load_pem_private_key(
        pem_bytes,
        password=None,  # 如果私钥有密码保护，请提供密码
        backend=default_backend()
    )

PUBLIC_KEY = load_public_key(PUBLIC_KEY_STR)
PRIVATE_KEY = load_private_key(PRIVATE_KEY_STR)

# 签名函数
def sign(data, private_key):
    data_bytes = data.encode('utf-8')
    signature = private_key.sign(
        data_bytes,
        padding.PKCS1v15(),
        hashes.MD5()
    )
    return base64.b64encode(signature).decode('utf-8')

# 验证函数
def verify(data, public_key, signature):
    data_bytes = data.encode('utf-8')
    signature_bytes = base64.b64decode(signature)
    try:
        public_key.verify(
            signature_bytes,
            data_bytes,
            padding.PKCS1v15(),
            hashes.MD5()
        )
        return True
    except Exception as e:
        return False


def decrypt(dec_data: str) -> str:
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.backends import default_backend
    aes_key="G/nZC/sAL8R/2VfFVJL/1g=="
    aes_iv="16jnea5cxx6f5mzl"
    UTF8 = 'utf-8'

    try:
        # 将密钥和偏移向量转换为字节
        key = aes_key.encode(UTF8)
        iv = aes_iv.encode(UTF8)

        # 解码 Base64 数据
        encrypted = base64.b64decode(dec_data)

        # 创建密码器
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
        decryptor = cipher.decryptor()

        # 解密数据
        decrypted = decryptor.update(encrypted) + decryptor.finalize()

        # 将解密后的数据转换为字符串
        return decrypted.decode(UTF8)
    except Exception as e:
        return None


# 主函数
def generate_msg(jdict):
    import time,secrets
    data = {
        "nonce": secrets.token_hex(16),
        "timestamp": int(time.time()*1000),
        "value": {
            "merchantNo": "Me00003282",
        }
    }
    data["value"].update(jdict)


    data_str = json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=False)

    signature = sign(data_str, PRIVATE_KEY)

    return signature, data_str

def get_haiyi_post(data, signature, path='catalog/list'):
    import requests
    import json

    # 目标 URL
    url = f'https://m.hykj.cn/locker-minimerchant/interface/{path}'

    # 可选的 headers
    headers = {
        'Content-Type': 'application/json',
        'Authorization': signature
    }

    # 发送 POST 请求
    response = requests.post(url, data=data, headers=headers)

    # 检查响应状态码
    response_data = None
    if response.status_code == 200:
        # 处理成功的响应
        response_data = response.json()
        response_data = json.dumps(response_data, indent=4, ensure_ascii=False)
    else:
        # 处理错误的响应
        print(f"Request failed with status code {response.status_code}")
        print("Response Content:", response.content)
    return response_data

def post_format(value, path):
    signature, data_str = generate_msg(value)
    return signature+"\r\n"+data_str, get_haiyi_post(data_str, signature, path) ,

def post_cataloglist_func(path):
    value = { "merchantNo": "Me00003282", "productNo": "CATALOG"}
    return post_format(value, path)

def post_querylist_func(path):
    value = {
        "merchantNo": "Me00003282",
        "productNo": "VISUAL",
        "id": "129772"
    }
    return post_format(value, path)

def post_querypage_func(path):
    value = {
        "merchantNo":"Me00003282",
        "productNo":"VISUAL",
        "pageNum":0,
        "pageSize":10
    }
    return post_format(value, path)

def post_cabinetquerylist_func(path):
    value = {"merchantNo":"Me00003282","productNo":"VISUAL"}
    return post_format(value, path)

def post_cabinetquerydetail_func(path):
    value = {"merchantNo":"Me00003282","productNo":"VISUAL", "cabinetSerialNumber": "WE10072055"}
    return post_format(value, path)

def post_weightgoodsconfig_func(path):
    value = {
        "productNo": "VISUAL",
        "merchantNo": "Me00003282",
        "cabinetSerialNumber": "W0010735",
        "cabinetGoodsConfigItemList": [
            {
                "productId": "129748",
                "latticeNumber": "W0010735-1",
                "price": 200
            },
            {
                "productId": "129772",
                "latticeNumber": "W0010735-2",
                "price": 100
            }
        ]
    }
    return post_format(value, path)

def post_cabinetaudio_func(path):
    value = {"merchantNo":"Me00003282","productNo":"VISUAL", "containerNumber": "WE10072055", "content": u"12345678"}
    return post_format(value, path)

from datetime import datetime, timedelta
def post_accountbalancequery_func(path):
    value = {
        "merchantNo": "Me00003282",
        "mobilePhone": "15670852416"
    }
    return post_format(value, path)

def post_cabinetorder_func(path):
    value = {
        "cabinetSerialNumber": "WE10072055",
        "startTime": (datetime.now()-timedelta(weeks=1)).strftime("%Y-%m-%d %H:%M:%S"),
        "endTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "productNo": "VISUAL",
        "merchantNo": "Me00003282",
        "operateType": "SHOPPING"
    }
    return post_format(value, path)

def post_ordercreate_func(path, otype="OPERATOR"):
    value = {
        "cabinetSerialNumber":"W0010735",
        "doorNumber":1,
        "merchantNo":"Me00003282",
        "operateType":otype,
        "orderCreateTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "orderNo": datetime.now().strftime("W%Y%m%d%H%M%S"),
        "payType":"MERCHANT_SELF_OPERATED_ORDER",
        "productNo":"VISUAL"
    }
    return post_format(value, path)

def post_ordervideo_func(order_no, path="order/orderVideo"):
    value = {
        "merchantNo":"Me00003282",
        "orderNo": order_no
    }
    return post_format(value, path)

haiyi_post_dict = {
    "post_cataloglist": [post_cataloglist_func, "catalog/list", "2.1.1 分类查询"],
    "post_queryList": [post_querylist_func, "weightGoods/queryList", "2.2.1 商品查询(id:129772/咪咪条)"],
    "post_queryPage": [post_querypage_func, "weightGoods/queryPage", "2.2.4 商品分页查询(0-10页)"],
    "post_cabinetquerylist": [post_cabinetquerylist_func, "cabinet/queryList", "2.3.1 货柜管理"],
    "post_cabinetquerydetail": [post_cabinetquerydetail_func, "cabinet/queryDetail", "2.3.2 查询货柜售卖信息"],
    "post_weightgoodsconfig": [post_weightgoodsconfig_func, "weightGoods/config", "2.3.3 售卖信息配置"],
    "post_cabinetaudio": [post_cabinetaudio_func, "cabinet/audio", "2.3.4 播报语音"],
    "post_accountbalancequery": [post_accountbalancequery_func, "account/balance/query", "2.5.1 账户资产查询"],
    "post_cabinetorder": [post_cabinetorder_func, "cabinet/order", "2.4.2 查询订单(1周)"],
    "post_ordercreate": [post_ordercreate_func, "order/create", "2.4.5 创建订单"]
}

if __name__ == "__main__":
    main()

